package com.ruoyi.order.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.model.PaymentReverse;
import com.ruoyi.adapayRecord.domain.AdapayRecord;
import com.ruoyi.adapayRecord.service.IAdapayRecordService;
import com.ruoyi.adapayRefund.domain.AdapayRefund;
import com.ruoyi.adapayRefund.service.IAdapayRefundService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.order.domain.OrderDo;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.order.mapper.StoreProductOrderMapper;
import com.ruoyi.order.domain.StoreProductOrder;
import com.ruoyi.order.service.IStoreProductOrderService;

/**
 * 订单信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-25
 */
@Service
public class StoreProductOrderServiceImpl implements IStoreProductOrderService
{
    @Autowired
    private StoreProductOrderMapper storeProductOrderMapper;
    @Autowired
    private IAdapayRecordService adapayRecordService;
    @Autowired
    private IAdapayRefundService adapayRefundService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询订单信息
     *
     * @param id 订单信息主键
     * @return 订单信息
     */
    @Override
    public StoreProductOrder selectStoreProductOrderById(Long id)
    {
        return storeProductOrderMapper.selectStoreProductOrderById(id);
    }

    /**
     * 查询订单信息列表
     *
     * @param storeProductOrder 订单信息
     * @return 订单信息
     */
    @Override
    public List<StoreProductOrder> selectStoreProductOrderList(StoreProductOrder storeProductOrder)
    {
        return storeProductOrderMapper.selectStoreProductOrderList(storeProductOrder);
    }




    /**
     * 新增订单信息
     *
     * @param storeProductOrder 订单信息
     * @return 结果
     */
    @Override
    public int insertStoreProductOrder(StoreProductOrder storeProductOrder)
    {
        storeProductOrder.setCreateTime(DateUtils.getNowDate());
        return storeProductOrderMapper.insertStoreProductOrder(storeProductOrder);
    }

    /**
     * 修改订单信息
     *
     * @param storeProductOrder 订单信息
     * @return 结果
     */
    @Override
    public int updateStoreProductOrder(StoreProductOrder storeProductOrder)
    {
        storeProductOrder.setUpdateTime(DateUtils.getNowDate());
        return storeProductOrderMapper.updateStoreProductOrder(storeProductOrder);
    }

    /**
     * 批量删除订单信息
     *
     * @param ids 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int deleteStoreProductOrderByIds(Long[] ids)
    {
        return storeProductOrderMapper.deleteStoreProductOrderByIds(ids);
    }


    /**
     * 批量逻辑删除订单信息
     *
     * @param ids 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int logicDeleteStoreProductOrder(Long[] ids,String delType,Long delUser)
    {
        return storeProductOrderMapper.logicDeleteStoreProductOrder(ids,delType,delUser);
    }

    /**
     * 删除订单信息信息
     *
     * @param id 订单信息主键
     * @return 结果
     */
    @Override
    public int deleteStoreProductOrderById(Long id)
    {
        return storeProductOrderMapper.deleteStoreProductOrderById(id);
    }
    /**
     * 获取一条用户在门店的订单
     * @param storeId
     * @param memberId
     * @return
     */
    public int selectFirstOrder(Long storeId,Long memberId){
        Map<String,Object> map=new HashMap<>();
        map.put("storeId",storeId);
        map.put("memberId",memberId);
        return storeProductOrderMapper.selectFirstOrder(map);
    }

    @Override
    public List<Long> selectNeedBilling() {
        return storeProductOrderMapper.selectNeedBilling();
    }

    @Override
    public List<StoreProductOrder> selectListByStoreId(Long id) {
        return storeProductOrderMapper.selectListByStoreId(id);
    }

    @Override
    public List<Long> selectClassifyList(Long storeId) {
        return storeProductOrderMapper.selectClassifyList(storeId);
    }

   /* @Override
    public List<StoreProductOrder> selectStoreProductOrderListByStore(StoreProductOrder order) {
        return storeProductOrderMapper.selectStoreProductOrderListByStore(order);
    }
*/
    @Override
    public StoreProductOrder selectVerify(String verifyCode,Long storeId) {
        return storeProductOrderMapper.selectVerify(verifyCode,storeId);
    }

    @Override
    public StoreProductOrder selectAftersale(String verifyCode,Long storeId) {
        return storeProductOrderMapper.selectAftersale(verifyCode,storeId);
    }

    @Override
    public List<Long> selectNeedRefund(Integer minute) {
        return storeProductOrderMapper.selectNeedRefund(minute);
    }

    @Override
    public void refund(StoreProductOrder order,AdapayRefund adapayRefund) {
        if(null==adapayRefund){
            return;
        }
        if(DicConstants.SYS_Y.getCode().equals(adapayRefund.getReqState())){
            //退款发起成功,具体结果等待回调
            order.setRefundStatus(DicConstants.REFUND_STATUS_Successed.getCode());
            order.setRefundPayOrderNo(adapayRefund.getRefundOrderNo());
//            order.setRefundPrice(order.getPayPrice());
        }else{
            //失败
            order.setRefundStatus(DicConstants.REFUND_STATUS_Refused.getCode());
            order.setRefundPayErrMsg(adapayRefund.getReqFailMsg());
        }

         storeProductOrderMapper.updateStoreProductOrder(order);
    }
    /**
     * 请求支付接口，相当于真实退款，需要再提交退款申请后24小时定时任务重判断订单没有进行核销，才能调用
     * @param orderId
     */
    @Override
    public AdapayRefund refundPay(Long orderId){
        StoreProductOrder order = this.selectStoreProductOrderById(orderId);
        if(null != order){
            if(!DicConstants.REFUND_STATUS_Pass.getCode().equals(order.getRefundStatus())) {
                //不处理
                return null;
            }
         /*
         这个是同步返回请求，不需要有退款中这个状态
          StoreProductOrder storeProductOrder=new StoreProductOrder();
            storeProductOrder.setId(orderId);
            storeProductOrder.setRefundPayStatus(DicConstants.REFUND_STATUS_Refunding.getCode());
            this.updateStoreProductOrder(storeProductOrder);*/
            String payOrderNo=order.getPayOrderNo();
            if(null!=payOrderNo){

                AdapayRecord adapayRecordQuery=new AdapayRecord();
                adapayRecordQuery.setPayOrderId(payOrderNo);
                adapayRecordQuery.setBelongType("product");
                List<AdapayRecord>  list=adapayRecordService.selectAdapayRecordList(adapayRecordQuery);
                if(list.size()>0){
                    //找到了支付记录
                    AdapayRecord adapayRecord= list.get(0);
                    String paymentId= adapayRecord.getPaymentId();
                    String notifyParam=adapayRecord.getNotifyParam();
                    //从通知里面获取真实支付金额进行退款
                    JSONObject notifyParamJSon= JSONObject.parseObject(notifyParam);
                    String pay_amt=notifyParamJSon.getString("pay_amt");
//                    Map<String, Object> refundParams = new HashMap<String, Object>();
                 /*   String refund_order_no="refund" + System.currentTimeMillis();
                    refundParams.put("refund_amt", pay_amt);
                    refundParams.put("refund_order_no", refund_order_no);*/
                    String refund_order_no="refund" + System.currentTimeMillis();
                    String domain=configService.selectConfigByKey("domain");
                    String notify_url=domain+"/prod-api/client/order/refundPayNotify";
                    /*refundParams.put("notify_url", notify_url);*/
                    String app_id=configService.selectConfigByKey("adpay_app_id");
                    Map<String, Object> reverseParams = new HashMap<>();
                    reverseParams.put("app_id", app_id);
                    reverseParams.put("payment_id",paymentId);
                    reverseParams.put("reverse_amt", pay_amt);
                    reverseParams.put("notify_url", notify_url);
                    reverseParams.put("order_no", refund_order_no);

                    AdapayRefund adapayRefund=new AdapayRefund();
                    adapayRefund.setRefundOrderNo(refund_order_no);
                    adapayRefund.setPaymentId(paymentId);
                    adapayRefund.setProductOrderId(orderId);
                    adapayRefund.setReqState(DicConstants.SYS_Y.getCode());
                    adapayRefund.setReqParam(reverseParams.toString());
                    Map<String, Object> paymentReverse =null;
                    try{
                        paymentReverse=  PaymentReverse.create(reverseParams);
                    }catch (Exception e){
                        e.printStackTrace();
                        adapayRefund.setReqState(DicConstants.SYS_N.getCode());
                        adapayRefund.setReqFailMsg(e.getMessage());
                        adapayRefundService.insertAdapayRefund(adapayRefund);
                        return adapayRefund;
                    }

                    adapayRefund.setResParam(paymentReverse.toString());
                    String error_code = (String) paymentReverse.get("error_code");
                    if (null != error_code) {
                        String error_msg = (String) paymentReverse.get("error_msg");
                        System.out.println("error_code:" + error_code + "............." + error_msg);
                        adapayRefund.setReqState(DicConstants.SYS_N.getCode());
                        adapayRefund.setReqFailMsg(error_msg);
                        adapayRefundService.insertAdapayRefund(adapayRefund);
                        return adapayRefund;
                    }
                    adapayRefundService.insertAdapayRefund(adapayRefund);
                    return adapayRefund;
                }
            }
        }
        return null;
    }

    @Override
    public List<StoreProductOrder> selectOverdue() {
        return storeProductOrderMapper.selectOverdue();
    }

    @Override
    public List<OrderDo> selectOrderList(OrderDo orderDo) {
        return storeProductOrderMapper.selectOrderList(orderDo);
    }
}
